package com.easyweb.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSONObject;
import com.easyweb.cache.StartUpListener;
import com.easyweb.common.Constants;
import com.easyweb.common.FileUtils;
import com.easyweb.common.PrimaryKeyGenerator;
import com.easyweb.common.PrintUtils;
import com.easyweb.model.Album;
import com.easyweb.model.ResultMsg;
import com.easyweb.model.Users;
import com.easyweb.service.AlbumService;

@Controller
@RequestMapping("/album")
public class AlbumController {
	
	private static Logger logger = LoggerFactory.getLogger(AlbumController.class);
	
	@Autowired
	private AlbumService albumService;
	
	@RequestMapping(value="/merge",method=RequestMethod.POST)
	public String addAlbum(HttpServletRequest request,HttpServletResponse response){
		Users user = (Users) request.getSession().getAttribute("user");
		if(user == null){
			request.setAttribute("result", JSONObject.toJSONString(new ResultMsg(Constants.STATUS_ERROR, Constants.EXPIRE)));
			return "back/frame";
		}
		//id
		String id = request.getParameter("id");
		//名称
		String title = request.getParameter("title");
		if(StringUtils.isEmpty(title)){
			request.setAttribute("result", JSONObject.toJSONString(new ResultMsg(Constants.STATUS_ERROR, StartUpListener.LANGUAGE.getProperty("title.notnull"))));
			return "back/frame";
		}
		String path = this.getClass().getClassLoader().getResource("/").getPath();
		path = path.replace("/WEB-INF/classes", "");
//		if(!path.endsWith(File.separator)){
//			path = path + File.separator;
//		}
		//上传图片
		List<String> uploadFile = null;
		try {
			uploadFile = FileUtils.uploadFile(request, path+Constants.COVERPATH+"/");
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("result", JSONObject.toJSONString(new ResultMsg(Constants.STATUS_ERROR, StartUpListener.LANGUAGE.getProperty("image.upload.fail"))));
			return "back/frame";
		}
		if(StringUtils.isEmpty(id)){
			if(uploadFile == null || uploadFile.size() == 0){
				request.setAttribute("result", JSONObject.toJSONString(new ResultMsg(Constants.STATUS_ERROR, StartUpListener.LANGUAGE.getProperty("image.upload.fail"))));
				return "back/frame";
			}
		}
		Album album = new Album();
		album.setTitle(title);
		if(StringUtils.isEmpty(id)){
			album.setId(PrimaryKeyGenerator.generatePrimaryKey());
			album.setCreateTime(new Date());
		}else{
			album.setId(id);
		}
		if(uploadFile != null && uploadFile.size() > 0){
			album.setCover(Constants.COVERPATH+"/"+uploadFile.get(0));
		}
		album.setEditTime(new Date());
		album.setCreateUser(null);
		int num = 0;
		if(StringUtils.isEmpty(id)){
			num = albumService.insertAlbum(album);
			logger.info("添加album成功");
		}else{
			num = albumService.updateAlbum(album);
			logger.info("更新album成功");
		}
		if(num > 0){
			request.setAttribute("result", JSONObject.toJSONString(new ResultMsg()));
		}else{
			request.setAttribute("result", JSONObject.toJSONString(new ResultMsg(Constants.STATUS_ERROR, StartUpListener.LANGUAGE.getProperty("error.unkonw"))));
		}
		return "back/frame";
	}
	
	@RequestMapping(value="/list",method=RequestMethod.GET)
	public void getAlbums(HttpServletRequest request,HttpServletResponse response){
		Users user = (Users) request.getSession().getAttribute("user");
		if(user == null){
			PrintUtils.printMsg(response, new ResultMsg(Constants.STATUS_ERROR, Constants.EXPIRE));
			return;
		}
		String pageSize = request.getParameter("pageSize");
		String pageStart = request.getParameter("pageStart");
		Map<String, Object> map = new HashMap<String, Object>();
		if(!StringUtils.isEmpty(pageSize)){
			map.put("pageSize", Integer.parseInt(pageSize));
		}
		if(!StringUtils.isEmpty(pageStart)){
			map.put("start",  Integer.parseInt(pageSize)*(Integer.parseInt(pageStart)-1));
		}
		List<Album> albums = albumService.getAlbums(map);
		PrintUtils.printMsg(response, albums);
	}
	@RequestMapping(value="/get",method=RequestMethod.GET)
	public void getAlbumById(HttpServletRequest request,HttpServletResponse response){
		Users user = (Users) request.getSession().getAttribute("user");
		if(user == null){
			PrintUtils.printMsg(response, new ResultMsg(Constants.STATUS_ERROR, Constants.EXPIRE));
			return;
		}
		String id = request.getParameter("id");
		if(StringUtils.isEmpty(id)){
			PrintUtils.printMsg(response, new ResultMsg(Constants.STATUS_ERROR, StartUpListener.LANGUAGE.getProperty("id.notnull")));
			return;
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", id);
		Album album = albumService.getAlbumById(map);
		PrintUtils.printMsg(response, album);
	}
	
	@RequestMapping(value="/del",method=RequestMethod.GET)
	public void delAlbumById(HttpServletRequest request,HttpServletResponse response){
		Users user = (Users) request.getSession().getAttribute("user");
		if(user == null){
			PrintUtils.printMsg(response, new ResultMsg(Constants.STATUS_ERROR, Constants.EXPIRE));
			return;
		}
		String id = request.getParameter("id");
		if(StringUtils.isEmpty(id)){
			PrintUtils.printMsg(response, new ResultMsg(Constants.STATUS_ERROR, StartUpListener.LANGUAGE.getProperty("id.notnull")));
			return;
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", id);
		Album album = albumService.getAlbumById(map);
		int num = albumService.deleteAlbumById(map);
		if(num > 0){
			logger.info("删除album成功");
			//删除关联的图片
			String path = this.getClass().getClassLoader().getResource("/").getPath();
			path = path.replace("/WEB-INF/classes", "");
			FileUtils.deleteFile(path+"/"+album.getCover());
			PrintUtils.printMsg(response, new ResultMsg());
		}else{
			PrintUtils.printMsg(response, new ResultMsg(Constants.STATUS_ERROR,null));
		}
	}
}
